﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebApiServices.Model;

namespace WebApiServices.Controllers {

    /// <summary>
    /// 产品信息查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[action]")]
    public class WorkOrderController : BaseController {

        private readonly IFreeSql _freeSql;
        private readonly ILogger<WorkOrderController> _logger;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 产品信息查询控制器
        /// </summary>
        /// <param name="freeSql"></param>
        /// <param name="logger"></param>
        public WorkOrderController(IFreeSql freeSql, ILogger<WorkOrderController> logger, IConfiguration configuration) {
            _freeSql = freeSql;
            _logger = logger;
            _configuration = configuration;
        }

        /// <summary>
        /// 根据箱码获取产品信息
        /// </summary>
        /// <param name="productRequest"></param>
        /// <returns></returns>
        [HttpPost(Name = "InsertWorkOrderInfo")]
        public IActionResult InsertWorkOrderInfo([FromBody] List<WorkOrderEntity> WorkOrderEntitys) {
            JObject keyValuePairs = new JObject();
            keyValuePairs.Add("success", "");
            keyValuePairs.Add("status", (int)ResultCode.SUCCESS);
            keyValuePairs.Add("msg", "");
            if (WorkOrderEntitys == null || WorkOrderEntitys.Count == 0) {
                keyValuePairs["msg"] = "参数不能为空";
            }
            foreach (var item in WorkOrderEntitys) {
                var list = _freeSql.Select<WorkOrderEntity>().Where(o => o.WorkOrderNumber == item.WorkOrderNumber).ToList();
                if (list.Count > 0) {
                    keyValuePairs["success"] = 0;
                    keyValuePairs["msg"] = $"工单号[{item.WorkOrderNumber}]在MES系统中已存在！";
                    return Content(JsonConvert.SerializeObject(keyValuePairs), "application/json");
                }
            }

            var affrows = _freeSql.Insert<WorkOrderEntity>(WorkOrderEntitys).ExecuteAffrows();
            if (affrows > 0) {
                keyValuePairs["success"] = 1;
                keyValuePairs["msg"] = "成功";
            }
            return Content(JsonConvert.SerializeObject(keyValuePairs), "application/json");
        }


    }
}
